package com.example.demo.service.impl;

import com.example.demo.entity.User;
import com.example.demo.entity.UserExample;
import com.example.demo.repository.RoleMapper;
import com.example.demo.repository.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.Conver2MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.relation.Role;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<User> selectUserIsLogin(User user) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(user.getUsername());
        String encodePwd = Conver2MD5.getMD5(user.getPassword());
        criteria.andPasswordEqualTo(encodePwd);
        return userMapper.selectByExample(userExample);
    }

    @Override
    public List<User> selectUserIsExisted(String username){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        return userMapper.selectByExample(userExample);
    }

    @Override
    public List<User> selectByEmail(String email) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andEmailEqualTo(email);
        return userMapper.selectByExample(userExample);
    }

    /**
     * 注册用户的同时 要给用户分配相应权限角色*/
    @Override
    @Transactional
    public int addUser(User user) {
        user.setPassword(Conver2MD5.getMD5(user.getPassword()));
        roleMapper.insertOne(user.getUsername());
        return userMapper.insertSelective(user);
    }

    @Override
    public int uploadUserInfo(User user) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(user.getUsername());
        return userMapper.updateByExampleSelective(user, userExample);
    }

    @Override
    public List<User> selectByPhone(String phone) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andPhonenumEqualTo(phone);
        return userMapper.selectByExample(userExample);
    }
}
